<?php
namespace app\admin\controller;

use app\common\model\RebateModel;
use think\Log;

/**
 * 返利
 *
 * @author jinxiwang
 *        
 */
class Rebate extends Base {

    /*
     * 初始化操作
     */
    public function _initialize() {
        $this->needLogin();
    }

    public function index() {
        $list = RebateModel::instance()->whereIn('type', [
            'TEAM',
            'LEADER'
        ])->select();
        $team = 0;
        $leader = [];
        foreach ($list as $item) {
            if ($item['type'] == 'TEAM') {

                if ($item['value']) {
                    $team = json_decode($item['value'], true);
                }
            } else if ($item['type'] == 'LEADER') {
                $leader = $item['value'];
            }
        }
        $this->assign('team', $team);
        $this->assign('leader', $leader);
        return $this->fetch();
    }

    public function person() {
        return $this->fetch();
    }

    public function person_edit() {
        return $this->returnResult(1);
    }

    public function team() {
        return $this->fetch();
    }

    public function team_edit() {
        $keys = $this->request->param('keys/a', []);
        $values = $this->request->param('values/a', []);

        Log::write('keys:' . print_r($keys, true));
        if (count($keys) == count($values)) {
            $result = [];
            for ($i = 0; $i < count($values); $i ++) {
                $result[$keys[$i]] = $values[$i];
            }
            ksort($result);
            Log::write('result:' . print_r($result, true));
            RebateModel::instance()->where('type', 'TEAM')->update([
                'value' => json_encode($result)
            ]);
            return $this->returnResult(1);
        }
        return $this->returnResult(0, '保存失败');
    }

    public function leader() {
        return $this->fetch();
    }

    public function leader_edit() {
        $value = $this->request->param('value', 0, 'floatval');
        RebateModel::instance()->where('type', 'LEADER')->update([
            'value' => $value
        ]);
        return $this->returnResult(1);
    }
}
